/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> largestValues(TreeNode root) {
        if (root == null) {
            return new ArrayList<Integer>();
        }
        List<Integer> res = new ArrayList<Integer>();
        dfs(res, root, 0);
        return res;
    }

    public void dfs(List<Integer> res,TreeNode root,int treeHeight) {
        //当还没有到达树的底部时，res中放，treeHeight=0时res.size()=0，放元素，直到放到树的高度
        //到最底层时（3层为例），treeHeight=2，size()=3，到else，吧treeHeight=2的下标值拿到与当前root.val做比较，拿到最大的，放入（下标，val）.
        if(treeHeight == res.size()) {
            res.add(root.val);
        } else {
            res.set(treeHeight,Math.max(res.get(treeHeight),root.val));//下标和值
        }
        if (root.left != null) {
            dfs(res, root.left, treeHeight + 1);
        }
        if (root.right != null) {
            dfs(res, root.right, treeHeight + 1);
        }
    }
}